import {Component, OnInit, ViewChild, OnDestroy, ChangeDetectorRef} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NgZone} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

import {format, formatDistance, formatRelative, subDays} from 'date-fns';
import {NzModalService} from 'ng-zorro-antd/modal';
import {defalutImg} from '../../../comm';
import {machineResultArrs} from '../love-recyc-manage.pipe';
import {machineInspectionRadios, purchaseChannelLists, MachineInspectionArrays} from '../machine-inspection-items';
import {LoveOrderManageService} from '../love-order-manage.service';
import {getLodop} from '../../../../assets/LodopFuncs';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, debounceTime, map, switchMap} from 'rxjs/operators';
import {CommonService} from '../../../services-common/common.service';

@Component({
  selector: 'app-inspected-machine-edit',
  templateUrl: './inspected-machine-edit.component.html',
  styleUrls: ['./inspected-machine-edit.component.scss']
})
export class InspectedMachineEditComponent implements OnInit, OnDestroy {
  @ViewChild('detailRef', {static: false}) detailRef: any;
  @ViewChild('offerModal', {static: false}) offerModal: any;
  @ViewChild('screenshotUpload', {static: false}) screenshotUpload: any;

  routeParams: any = {};
  fallback: string = defalutImg;
  detailData: any = {};

  // 能否验机
  isMachineInfos: any = {
    canMachineRadios: [...machineInspectionRadios],
    canMachineSelected: '',
    interruptTips: '', // 中断Tips

    type: '', // 0-可正常验机 1-准新机  2-部分验机
    status: '', // 1-验机中断 不传值默认验机完成
    interruptRemarks: '', // 中断原因
    isResultGoods: '', // 是否退货 0:否、1:是
    resultQuantity: '', // 退货数量
    isFreight: 1, // 邮费承担 0我司承担 1用户承担
    followerContent: '' // 跟进信息
  };
  minQuantitySize: number = 1; // 退货数量最少

  // 基础信息
  basicInfos: any = {
    isInputLoading: false,
    nzFilterOption: (): boolean => true, // 机型搜索
    recycleModelOptions: [], // 机型下拉
    recycleModelValue: '',
    recycleModelName: '', // 机型名称
    capacityOptions: [], // 容量下拉
    capacityValue: '',
    colorOptions: [], // 机型颜色下拉
    colorValue: '',
    buyType: '', // 购买渠道
    net: '', // 网络制式
    imel: '', // IMEI
    phoneSerialNumber: '', // 机器序列号
    guaranteeTime: '', // 保修截止日期
    batteryHealth: '', // 电池健康值
    chargeCount: '' // 充电次数
  };
  basicHaves: any = {
    haveModel: false, // 机型--有无此项 0-无此项 1-有
    haveStore: false, // 容量--有无此项
    haveColour: false, // 颜色--有无此项
    haveBuyType: false, // 渠道--有无此项
    haveNet: false, // 网络制式--有无此项
    haveImel: false, // IMEI--有无此项
    havePhoneSerialNumber: false, // 序列号--有无此项
    haveGuaranteeTime: false, // 保修截止日期--有无此项
    haveBatteryHealth: false, // 电池健康值--有无此项
    haveChargeCount: false // 充电次数--有无此项
  };
  // 购买渠道
  payChannelRadios: any = [...purchaseChannelLists];
  // 电池健康Options
  batteryOptions: any = [];

  // 机型options<请求防抖>
  searchChange$ = new BehaviorSubject('');

  // 验机项
  termLists: any = [];
  // 图片补充
  isImgVisible: boolean = false;
  updateImgItem: any = {};
  modalImgLists: any = [];
  quickImgLists: any = [];

  // 验机图片
  isSpinning: boolean = false;
  machineImgList: any = [];

  // 爱思截图
  screenshotImgList: any = [];

  // 验机结果options
  resultArrs: any = [...machineResultArrs];
  // 验机结果
  resultInfos: any = {
    restype: '', // 验机结果
    restypeRemarks: '', // 不支持回收原因
    price: '', // 验机价格
    checkNote: '', // 验机师备注
    checkExplain: '', // 验机说明
    libraryId: '', // 库位
    colourId: '', // 成色标识id[C端]
    colourName: '', // 成色标识name[C端]
    colourIdB: '', // 成色标识id[B端]
    colourNameB: '' // 成色标识name[B端]
  };

  // 验机中断原因
  interruptArrs: any = [
    {value: '0', label: '有屏锁-需外呼', tips: '有屏锁需客服外呼'},
    {value: '1', label: '有ID-需外呼', tips: '需客服外呼'},
    {value: '2', label: '其他原因-无需外呼', tips: ''},
    {value: '3', label: '其他原因-需外呼', tips: ''}
  ];
  interruptSelected: any = [];

  // 不支持回收原因
  notSupportReason: any = [
    {value: '0', label: '电池严重膨胀', tips: '电池外包装纸幅度大于5mm'},
    {value: '1', label: '仿冒产品', tips: '销售企业未在工商部门注册;设备未取得工信部入网许可;设备外壳及系统内无品牌型号等信息;常见品牌的仿冒设备'},
    {value: '2', label: '已开启查找我的手机功能', tips: '已开启查找我的手机功能，无法提供购买凭证、人脸核身等信息'},
    {value: '3', label: 'ID激活锁与屏幕锁', tips: '1、有ID激活锁、隐藏ID、屏幕锁、手机已停用（无法提供购买凭证、人脸核身等信息）2、手机为丢失模式'},
    {value: '4', label: '非验机商品', tips: '1、不能开机的套壳机/模型样机;2、非正常收录的3C产品，如数据线，充电头、台式电脑等'},
    {value: '5', label: '缺少核心组件', tips: '缺主板'},
    {
      value: '6',
      label: '无法验机',
      tips: '1、不能开机的套壳机/模型样机 2、非正常收录的3C产品，如数据线，充电头、台式电脑等 3、无法开机且主板有大修（飞线、缺少屏蔽罩、明显焊油，主板断裂、明显弯曲、 缺少主板元器件）并且内部缺少零部件3个及以上（电池、 副板、摄像头、音频组件、指纹模组、振子马达）。'
    },
    {value: '7', label: '监管机', tips: '打开“设置”或者“关于本机”，如果显示“此iPhone受xxx监督管理”，则说明该设备为监管机;监管机存在较高的法律风险，所有业务线统一不收监管机;意外回收的监管机，勾选有ID，有话说勾选话术'}
  ];
  reasonTips: string = '';
  // 网络制式
  networkOptions: any = [
    {value: '0', label: '全网通'},
    {value: '1', label: '双网通'},
    {value: '2', label: '移动版'},
    {value: '3', label: '联通版'},
    {value: '4', label: '电信版'},
    {value: '5', label: '不支持'},
    {value: '6', label: 'WiFi版'}
  ];

  // 查看评估详情 Modal
  previewParams: any = {
    moduleId: '', // 机型ID
    evalList: [], // 对比项
    umname: '', // 机型名称
    totalNum: 0 // 预估合计
  };
  // subLoading...
  subLoading: boolean = false;

  // 库位options
  locationOptions: any = [];

  // [C端]成色options
  conditionOptions: any = [];
  // [B端]成色options
  conditionOptionsb: any = [];

  // 打印
  isPrint: boolean = false;
  LODOP: any;
  deviceInfo = {
    type: '',
    color: '',
    memory: '',
    version: '',
    network: '',
    serial: '',
    serialNumber: '',
    imei: '',
    chargeCount: '',
    batteryHealth: '',
  };

  // 出价参考Modal
  consultVisible: boolean = false;
  consultLoading: boolean = false;
  // 用户评估
  userEvaluationData: any = {};

  // IMEI查询
  imeiLoading = false;
  isHasImei = -1; // -1：不显示 0：不存在 1：存在

  constructor(
    private ngZone: NgZone,
    private changeDetectorRef: ChangeDetectorRef,
    private activatedRoute: ActivatedRoute,
    private nzModalService: NzModalService,
    private message: NzMessageService,
    private commonService: CommonService,
    private services: LoveOrderManageService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
      this.previewParams = res.previewParams ? JSON.parse(res.previewParams) : [];
      this.minQuantitySize = res?.machineListSize ? (Number(res?.machineListSize) + 1) : 1;
    });
  }

  async ngOnInit() {
    await this.getLocationOptions();

    // 电池健康
    this.batteryOptions = await this.commonService.getDictList('es_battery_health');
    // C端成色
    this.conditionOptions = await this.getConditionOptions('machine_condition');
    // B端成色
    this.conditionOptionsb = await this.getConditionOptions('machine_condition_b');

    /**
     * 机型选择防抖
     * ----------------------------------------------------------------
     */
    this.searchChange$
      .asObservable()
      .pipe(debounceTime(500))
      .subscribe((value: any) => {
        if (!value) {
          this.basicInfos.recycleModelOptions = [];
          return;
        }
        this.getRecycleModelOptions(value);
      });

    if ([1, 2].includes(Number(this.routeParams.type))) {
      this.getReportDetailData();
    } else {
      let tmpLists = JSON.parse(JSON.stringify(MachineInspectionArrays));
      this.defaultSelectItem(tmpLists);
      this.termLists = tmpLists || [];
    }

    // 默认设置机型(非批量回收、新增)
    if (['1', '3'].includes(this.routeParams.orderWay) && this.routeParams.type == '0') {
      // 机型详情
      const {modelId, modelName}: any = !this.commonService.isEmpty(this.routeParams.modelInfos) ? JSON.parse(this.routeParams.modelInfos) : {};
      await this.getRecycleModelOptions(modelName);
      this.modelChange(modelId);

      this.basicInfos.recycleModelValue = modelId; // 机型ID
      this.basicInfos.recycleModelName = modelName; // 机型名称
    }

    setTimeout(() => {
      this.LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
      if (!this.LODOP) {
        this.message.warning('未安装打印插件');
        return;
      }
      let count = 0;
      for (let i = 0; i < this.LODOP.GET_PRINTER_COUNT(); i++) {
        if (this.LODOP.GET_PRINTER_NAME(i).includes('BTP')) {
          count += 1;
          this.LODOP.SET_PRINTER_INDEXA(i);
        }
      }
      if (count === 0) {
        this.message.warning('未找到包含BTP的打印机，请手动设置');
      } else if (count === 1) {
        this.message.success('打印机初始化成功');
      } else if (count > 1) {
        this.message.success('找到两台包含BTP的打印机，将选择最后一台作为默认设备');
      }
    }, 1000);
  }

  ngOnDestroy(): void {
    this.searchChange$.unsubscribe();
  }

  // 选项默认选择设置
  defaultSelectItem(arr: Array<any>) {
    arr.forEach((item: any) => {
      if (item.children) {
        this.defaultSelectItem(item.children);
      } else {
        if (item.optionType && item.optionType === 1) {
          item.radioSelected = '0';
        }
        if (item.optionType && item.optionType === 2) {
          item.checkedSelected.push('0');
          item.options[0].checked = true;
        }
      }
    });
  }

  // 查询库位options<启用>
  async getLocationOptions() {
    let params = {
      status: 0,
      page: 1,
      pageSize: 100000
    };
    const res: any = await this.services.getLocationList(params);
    if (res.code == 0) {
      const {records} = res.data || {};
      this.locationOptions = records || [];
    } else {
      this.locationOptions = [];
    }
  }

  // 获取C端成色
  async getConditionOptions(codeStr: string) {
    const res: any = await this.commonService.dictListData(codeStr);
    if (res.code == 0) {
      const {list} = res.data || {};
      return list || [];
    } else {
      return [];
    }
  }

  // 查看验机详情
  async getReportDetailData() {
    let params: any = {};
    if (this.routeParams?.againMachine) {
      params.phoneCode = this.routeParams?.phoneCode;
      params.source = 1;
    } else {
      params.id = this.routeParams.id;
    }
    const loadId = this.message.loading('数据加载中..', {nzDuration: 0}).messageId;
    const res: any = await this.services.getReportDetail(params);
    this.message.remove(loadId);

    if (res.code == 0) {
      const {data} = res || {};

      this.detailData = data || {};

      // 验机状态
      // if (data.type != '' || data.type != null || data.type != undefined) {
      //   this.isMachineInfos.canMachineSelected = data.type;
      // }
      this.isMachineInfos.canMachineSelected = data.status || '';
      this.isMachineInfos.status = data.status || '';
      this.isMachineInfos.isResultGoods = String(data.isResultGoods) || ''; // 是否退货 0:否、1:是
      this.isMachineInfos.resultQuantity = data.resultQuantity || ''; // 退货数量
      this.isMachineInfos.isFreight = data.isFreight; // 邮费承担 0我司承担 1用户承担
      this.isMachineInfos.followerContent = data.followerContent || ''; // 跟进信息
      if (data.status == 1) {
        // this.isMachineInfos.canMachineSelected = 3;
        // this.isMachineInfos.status = data.status || ''; // 1-验机中断 不传值默认验机完成
        this.isMachineInfos.interruptRemarks = data.interruptRemarks || ''; // 中断原因str
        this.interruptSelected = data.interruptRemarks.split(','); // 原因arr selected

        let tempStr = this.interruptArrs.filter((item: any) => this.interruptSelected.includes(item.label)).map((tag: any) => tag.tips);
        this.isMachineInfos.interruptTips = tempStr || '';
      }

      // 基础信息
      this.basicInfos.recycleModelName = data.modelName || ''; // 机型名称
      if (data.modelName) {
        await this.getRecycleModelOptions(data.modelName); // 机型list
      }
      this.basicInfos.recycleModelValue = data.modelId; // 机型ID
      this.modelChange(this.basicInfos.recycleModelValue);
      this.basicInfos.capacityValue = data.store || ''; // 容量
      this.basicInfos.colorValue = data.colour || ''; // 颜色

      this.basicInfos.buyType = data.buyType; // 购买渠道
      this.basicInfos.net = data.net; // 网络制式
      this.basicInfos.imel = data.imel; // IMEI
      this.basicInfos.phoneSerialNumber = data.phoneSerialNumber; // 序列号
      this.basicInfos.guaranteeTime = data.guaranteeTime; // 保修截至时间
      this.basicInfos.batteryHealth = data.batteryHealth; // 电池健康值
      this.basicInfos.chargeCount = data.chargeCount; // 充电次数
      // 基础信息有无此项
      for (let key in this.basicHaves) {
        this.basicHaves[key] = data[key] == 0 ? true : false;
      }

      // 验机项
      this.termLists = data.context ? JSON.parse(data.context) : [];

      // 验机图片
      this.machineImgList = data.img ? data.img.split(',') : [];
      // 爱思截图
      this.screenshotImgList = data.asImg ? data.asImg.split(',') : [];

      // 验机结果
      this.resultInfos.restype = data.restype || ''; // 验机结果
      this.resultInfos.restypeRemarks = data.restypeRemarks || ''; // 不支持回收原因
      if (data.restypeRemarks) {
        this.reasonTipsFilter(); // 原因Tips
      }
      this.resultInfos.price = data.price || '0'; // 验机价格
      this.resultInfos.checkNote = data.checkNote || ''; // 验机师备注
      this.resultInfos.checkExplain = data.checkExplain || ''; // 验机说明
      this.resultInfos.libraryId = data.libraryId || ''; // 库位
      this.resultInfos.colourId = data.colourId || ''; // 成色标识id[C-端]
      this.resultInfos.colourName = data.colourName || ''; // 成色标识[C-端]
      this.resultInfos.colourIdB = data.colourIdB || ''; // 成色标识id[B-端]
      this.resultInfos.colourNameB = data.colourNameB || ''; // 成色标识[B-端]
    } else {
      this.message.error(res.message);
    }
  }

  // 查询机型配置list source: 1 已配置价格
  async getRecycleModelOptions(searchName: string) {
    this.basicInfos.isInputLoading = true;
    const res: any = await this.services.getEditModelList({name: searchName, source: 1});
    this.basicInfos.isInputLoading = false;
    if (res.code == 0) {
      const {records} = res.data || {};
      this.basicInfos.recycleModelOptions = records || [];
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ---------------------------------------------------------------
   * 能否验机
   * ---------------------------------------------------------------
   */
  radioChange(value: any) {
    this.isMachineInfos.status = value;
    this.isMachineInfos.interruptRemarks = '';
    this.isMachineInfos.followerContent = '';
    this.isMachineInfos.isResultGoods = '';
    this.isMachineInfos.resultQuantity = '';
    this.isMachineInfos.isFreight = '';
    this.interruptSelected = [];

    // 无法验机默认退货
    if (value == 5) {
      this.isMachineInfos.isResultGoods = '1';
      this.isMachineInfos.isFreight = 1;
    }
  }

  reasonChange(value: any) {
    let tmpArr = [];
    tmpArr = this.interruptArrs.filter((item: any) => value.includes(item.label)).map((tag: any) => tag.tips);
    // tips
    this.isMachineInfos.interruptTips = tmpArr.join(',');
    // 原因
    this.isMachineInfos.interruptRemarks = value.join(',');
  }

  // 能否退货change
  isReturnGoodsChange(value: any) {
    this.isMachineInfos.resultQuantity = '';
    this.isMachineInfos.isFreight = 1;
  }

  /**
   * ---------------------------------------------------------------
   * 基础信息
   * ---------------------------------------------------------------
   */
  searchModel(value: any) {
    this.searchChange$.next(value);
  }

  modelChange(value: any) {
    let tmpObj: any;
    tmpObj = this.basicInfos.recycleModelOptions.find((item: any) => item.id == value);
    this.basicInfos.capacityValue = '';
    this.basicInfos.colorValue = '';
    this.basicInfos.capacityOptions = tmpObj?.memory ? tmpObj.memory.split(',') : [];
    this.basicInfos.colorOptions = tmpObj?.color ? tmpObj.color.split(',') : [];
    this.basicInfos.recycleModelName = tmpObj?.name || '';

    if (this.basicHaves.haveModel && value) {
      this.basicHaves.haveModel = false;
    }
  }

  /**
   * ---------------------------------------------------------------
   * 验机项
   * ---------------------------------------------------------------
   */
  // 多选change
  checkChange(children: any, optionItem: any) {
    // 选择正常清除其余所选
    if (optionItem.value == '0') {
      if (optionItem.checked) {
        children.options.forEach((element: any) => {
          element.checked = element.value == '0' ? true : false;
        });
      } else {
        children.options[0].checked = false;
      }
    } else {
      children.options[0].checked = false;
    }
    children.checkedSelected = children.options.filter((tag: any) => {
      return tag.checked;
    }).map((m: any) => {
      return m.value;
    }) || [];

    if (children.checkedSelected.length) {
      children.noneItem = false;
    }
  }

  // 单选change
  radioGroupChange(item: any) {
    if (item.radioSelected != '' && item.noneItem) {
      item.noneItem = false;
    }
  }

  // 无此项change
  tagItemChange(item: any) {
    if (item.radioSelected) {
      item.radioSelected = '';
    }
    if (item.checkedSelected) {
      item.checkedSelected = [];
      item.options.map((item: any) => item.checked = false);
    }
  }

  /**
   * ---------------------------------------------------------------
   * 图片补充
   * ---------------------------------------------------------------
   */
  showImgModal(item: any) {
    this.isImgVisible = true;
    this.updateImgItem = item;
    this.modalImgLists = [];
    this.modalImgLists = [...item.imgLists];

    this.quickImgLists = [];
    if (this.machineImgList.length) {
      this.machineImgList.forEach((tag: any) => {
        let obj: any = {
          url: tag,
          checked: false
        };
        if (this.modalImgLists.includes(tag)) {
          obj.checked = true;
        }
        this.quickImgLists.push(obj);
      });
    }
  }

  // 图片补充 Modal 快捷选图勾选Change
  quickImgChange(val: any, item: any) {
    if (val) {
      this.modalImgLists.push(item.url);
    } else {
      let tmpIndex = this.modalImgLists.findIndex((img: any) => img === item.url);
      this.modalImgLists.splice(tmpIndex, 1);
    }
  }

  // 图片补充 Modal Delete Change
  imgModalChange(value: any) {
    this.quickImgLists.forEach((item: any) => {
      if (item.url === value) {
        item.checked = false;
      }
    });
  }

  subImgData() {
    this.updateImgItem.imgLists = this.modalImgLists;
    this.isImgVisible = false;
  }

  // 验机结果
  resultChange(value: any) {
    this.resultInfos.restypeRemarks = '';
  }

  // 保存
  informSaving() {
    if (String(this.isMachineInfos.canMachineSelected) == '') {
      this.message.warning('请先选择能否验机');
      return;
    }

    // 验机状态为无法验机需选择是否需要退货
    if (this.isMachineInfos.canMachineSelected == 5 && String(this.isMachineInfos.isResultGoods) == '') {
      this.message.warning('请先选择是否需要退货');
      return;
    }
    if (this.isMachineInfos.canMachineSelected == 5 && this.isMachineInfos.isResultGoods == '1' && !this.isMachineInfos.resultQuantity) {
      this.message.warning('请输入退货数量');
      return;
    }
    if (this.isMachineInfos.canMachineSelected == 5 && this.isMachineInfos.isResultGoods == '1' && ![0, 1].includes(this.isMachineInfos.isFreight)) {
      this.message.warning('请选择邮费承担');
      return;
    }

    // 能否验机选择(中断、无法验机)可直接提交、完成不可直接提
    if (this.isMachineInfos.canMachineSelected == '3') {
      if (!this.verifData()) {
        return;
      }
    }

    // 基础信息有无此项 0-无此项 1-有
    let tmpHaves: any = {};
    Object.keys(this.basicHaves).forEach((key: any) => {
      tmpHaves[key] = this.basicHaves[key] ? 0 : 1;
    });

    // 验机项处理
    let newTermLists: any = [];
    this.termLists.forEach((item: any) => {
      if (item.id == 1) {
        newTermLists = [...item.children];
      }
      if (item.id == 2) {
        newTermLists.push({
          id: item.children[0].id,
          title: '拆修情况',
          children: item.children[0].children
        });
      }
      if (item.id == 3) {
        newTermLists.push({
          id: item.id,
          title: '功能问题',
          children: this.concatArrayData(item.children)
        });
      }
    });

    let params = {
      type: this.isMachineInfos.type, // 能否验机 0-可正常验机 1-准新机 2-部分验机 **** Import 注：暂无用 ****
      status: this.isMachineInfos.status, // 1-验机中断 不传值默认验机完成
      interruptRemarks: this.isMachineInfos.interruptRemarks, // 验机中断原因
      followerContent: this.isMachineInfos.followerContent || '', // 验机状态跟进
      isResultGoods: this.isMachineInfos.isResultGoods, // 验机状态是否需要退货
      resultQuantity: this.isMachineInfos.resultQuantity, // 验机状态--退货数量
      isFreight: this.isMachineInfos.isFreight, // 验机状态--邮费承担

      modelId: this.basicInfos.recycleModelValue, // 机型ID
      modelName: this.basicInfos.recycleModelName, // 机型名称
      store: this.basicInfos.capacityValue, // 存储容量
      colour: this.basicInfos.colorValue, // 颜色
      buyType: this.basicInfos.buyType, // 渠道 1-国行 2-港澳台版本 3-其他版本无锁 4-其他版本有锁
      net: this.basicInfos.net, // 网络制式
      imel: this.basicInfos.imel, // IMEL
      phoneSerialNumber: this.basicInfos.phoneSerialNumber, // 序列号
      guaranteeTime: this.basicInfos.guaranteeTime ? format(new Date(this.basicInfos.guaranteeTime), 'yyyy-MM-dd') + ' 00:00:00' : '', // 保修截至时间
      batteryHealth: !this.commonService.isEmpty(this.basicInfos.batteryHealth) ? this.basicInfos.batteryHealth : '', // 电池健康值
      chargeCount: !this.commonService.isEmpty(this.basicInfos.chargeCount) ? this.basicInfos.chargeCount : '', // 充电次数
      ...tmpHaves, // 基础信息s--是否无此项

      okey: this.routeParams.okey, // 订单编号
      context: JSON.stringify(this.termLists), // 验机项arr<三级>
      newContext: JSON.stringify(newTermLists), // 验机项arr<二级>
      img: this.machineImgList.join(','), // 验机图片
      asImg: this.screenshotImgList.join(','), // 爱思截图

      restype: !this.routeParams?.againMachine ? this.resultInfos.restype : '', // 验机结果(!!!注意：重新验机不需要)
      restypeRemarks: !this.routeParams?.againMachine ? this.resultInfos.restypeRemarks : '', // 验机结果--不支持回收原因
      price: this.resultInfos.price, // 验机价格
      checkNote: this.resultInfos.checkNote || '', // 验机师备注
      checkExplain: this.resultInfos.checkExplain || '', // 验机说明
      libraryId: this.resultInfos.libraryId || '', // 库位
      colourId: this.resultInfos.colourId || '', // 成色标识ID[C-端]
      colourName: this.resultInfos.colourName || '', // 成色标识[C-端]
      colourIdB: this.resultInfos.colourIdB || '', // 成色标识ID[B-端]
      colourNameB: this.resultInfos.colourNameB || '' // 成色标识[-B端]
    };

    if (['1', '2'].includes(this.routeParams.type) && !this.routeParams?.againMachine) {
      // update （二手重新验机入库不需要!!!）
      params.id = this.routeParams.id;
      params.phoneCode = this.detailData.phoneCode;
    }

    // 重新验机入库确认 !!!
    if (this.routeParams?.againMachine) {
      params.source = 6; // 来源不为空表示重新回收
      params.oldPhoneCode = this.detailData.phoneCode; // 来源不为空表示重新回收

      this.nzModalService.confirm({
        nzTitle: '提示',
        nzContent: '原机器信息将会彻底弃用，操作后将生成新的机器编码和信息，确定将该机器重新验机入库?',
        nzOkText: '确认',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: () => {
          this.submitInterface(params);
        },
        nzCancelText: '取消'
      });
      return;
    }

    this.submitInterface(params);
  }

  async submitInterface(params: any) {
    this.subLoading = true;
    const res: any = await this.services.updateReportData(params);
    this.subLoading = false;
    if (res.code == 0) {
      if (this.isPrint) {
        // let tmpObjs: any = res.data.find((ele: any) => ele.modelId == this.basicInfos.recycleModelValue);
        this.print(res?.data || {});
      }
      // return
      this.message.success('操作成功');
      this.back();
    } else {
      this.message.error(res.message);
    }
  }

  // concat array<功能问题>
  concatArrayData(arrs: any[]) {
    if (arrs.length) {
      let tmpArr: any = [];
      arrs.forEach((item: any) => {
        tmpArr = tmpArr.concat(item.children);
      });
      return tmpArr;
    }
  }

  // 查看评估详情
  viewAssessment() {
    this.detailRef.getSubjectList();
    this.detailRef.isVisible = true;
  }

  // back
  back() {
    history.back();
  }

  // 当前项是否已操作
  isOverItem(item: any) {
    if (item.optionType == 1 && (item.radioSelected || item.noneItem)) {
      return true;
    } else if (item.optionType == 2 && (item.checkedSelected.length || item.noneItem)) {
      return true;
    } else {
      return false;
    }
  }

  // 验证verif data
  verifData() {
    if (!this.verifBasicData()) {
      // 基础信息填写验证
      return false;
    } else if (!this.verifContrastData(this.termLists)) {
      // 验机项填写验证
      return false;
    } else if (!this.resultInfos.restype && !this.routeParams?.againMachine) {
      this.message.warning('请先选择验机结果');
      return false;
    } else if (this.resultInfos.restype && this.resultInfos.restype == 15 && !this.resultInfos.restypeRemarks && !this.routeParams?.againMachine) {
      this.message.warning('请选择不支持回收原因');
      return false;
    } else if (this.resultInfos.price === '' || this.resultInfos.price === null || this.resultInfos.price === undefined) {
      this.message.warning('请输入验机价格');
      return false;
    } else if (this.commonService.isEmpty(this.resultInfos.colourId)) {
      this.message.warning('请选择C端成色');
      return false;
    } else if (this.commonService.isEmpty(this.resultInfos.colourIdB)) {
      this.message.warning('请选择B端成色');
      return false;
    } else {
      return true;
    }
  }

  // 基础信息验证
  verifBasicData() {
    if (!this.basicInfos.recycleModelValue && !this.basicHaves.haveModel) {
      this.message.warning('基础信息：请选择机型');
      return false;
    } else if (!this.basicInfos.capacityValue && !this.basicHaves.haveStore) {
      this.message.warning('基础信息：请选择容量');
      return false;
    } else if (!this.basicInfos.colorValue && !this.basicHaves.haveColour) {
      this.message.warning('基础信息：请选择颜色');
      return false;
    } else if (!this.basicInfos.buyType && !this.basicHaves.haveBuyType) {
      this.message.warning('基础信息：请选择购买渠道');
      return false;
    } else if (!this.basicInfos.net && !this.basicHaves.haveNet) {
      this.message.warning('基础信息：请选择网络制式');
      return false;
    } else if (!this.basicInfos.imel && !this.basicHaves.haveImel) {
      this.message.warning('基础信息：请输入IMEI');
      return false;
    } else if (!this.basicInfos.phoneSerialNumber && !this.basicHaves.havePhoneSerialNumber) {
      this.message.warning('基础信息：请输入序列号');
      return false;
    } else if (!this.basicInfos.guaranteeTime && !this.basicHaves.haveGuaranteeTime) {
      this.message.warning('基础信息：请选择保修截至时间');
      return false;
    } else if (this.commonService.isEmpty(this.basicInfos.batteryHealth) && !this.basicHaves.haveBatteryHealth) {
      this.message.warning('基础信息：请输入电池健康值');
      return false;
    } else if (this.commonService.isEmpty(this.basicInfos.chargeCount) && !this.basicHaves.haveChargeCount) {
      this.message.warning('基础信息：请输入充电次数');
      return false;
    } else {
      return true;
    }
  }

  // 验机项填写验证
  verifContrastData(array: any): any {
    let tmpBool = true;
    for (let i = 0; i < array.length; i++) {
      for (let j = 0; j < array[i].children.length; j++) {
        let tmpObj = array[i].children[j].children.find((tag: any) => {
          return tag.optionType == 1 ? (!tag.radioSelected && !tag.noneItem) : (!tag?.checkedSelected?.length && !tag.noneItem);
        });
        if (tmpObj) {
          this.message.warning(`${array[i].children[j]?.title}: ${tmpObj.subject} <b class="color-red">未填写</b>`);
          tmpBool = false;
          // break;
          return;
        } else {
          tmpBool = true;
        }
      }
    }
    return tmpBool;
  }

  // 打印
  print(data: any) {
    let channelObj = this.payChannelRadios.find((item: any) => {
      return item.value == data.buyType;
    });
    this.deviceInfo = {
      type: data.modelName, // 名称
      color: data.colour, // 颜色
      memory: data.store, // 内存
      version: channelObj?.label || '--', // 购买渠道版本
      network: data.net, // 网络
      serial: data.phoneCode,
      serialNumber: data.phoneSerialNumber,
      imei: data?.imel || '',
      chargeCount: data?.chargeCount || '',
      batteryHealth: data?.batteryHealth || '',
    };


    setTimeout(() => {
      this.LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
      this.LODOP.SET_LICENSES('', 'D4E01F380814536C3C4887A0707CBBD4A4B', '', '');
      this.LODOP.SET_PRINT_PAGESIZE(1, 500, 250);
      this.LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementById('printDeviceInfo')?.innerHTML);
      this.LODOP.PRINT();
    });
    // if (this.dbclick) {
    //   clearTimeout(this.dbclick);
    //   this.dbclick = null;
    //   this.LODOP.PREVIEW();
    //   return;
    // }
    // this.dbclick = setTimeout(() => {
    //   this.LODOP.PRINT();
    //   this.dbclick = null;
    // }, 500);
  }

  /**
   * 是否可编辑(当前验机师、未推送)
   * isPush 0：没推送 1：推送了
   * @returns
   */
  isEditBtn() {
    // 重新验机都可编辑
    if (this.routeParams?.againMachine) {
      return false;
    }

    let userInfo: any = localStorage.getItem('userInfos') ? JSON.parse(localStorage.getItem('userInfos') as any) : {};
    if (
      (this.detailData?.checkName && this.detailData?.checkName != userInfo?.realName) ||
      (!this.commonService.isEmpty(this.detailData?.isPush)) && this.detailData?.isPush == 1 ||
      !this.termLists.length ||
      [5].includes(this.detailData.status) ||
      ([15, 16, 18].includes(Number(this.routeParams.ostat)) && this.detailData?.isActivation == 0) ||
      [19, 20, 22, 23, 24, 25, 91].includes(Number(this.routeParams.ostat))
    ) {
      return true;
    } else {
      return false;
    }
  }

  // 不支持回收原因tips
  reasonTipsFilter() {
    let tmpObj: any = {};
    if (this.resultInfos.restypeRemarks) {
      tmpObj = this.notSupportReason.find((item: any) => item.label == this.resultInfos.restypeRemarks);
    }
    this.reasonTips = tmpObj?.tips || '--';
  }

  /**
   * 成色选择change
   * @param value
   * @param str
   */
  conditionChange(value: any, str: string) {
    let tmpArrs = (str.toLocaleUpperCase() == 'C' ? this.conditionOptions : this.conditionOptionsb) || [];
    let obj = tmpArrs.find((item: any) => item.id == value);
    switch (str.toLocaleUpperCase()) {
      case 'C':
        this.resultInfos.colourName = obj.name || '';
        return;
      case 'B':
        this.resultInfos.colourNameB = obj.name || '';
        return;
    }
  }

  /**
   * ----------------------------------------------------------------
   * 基础信息处理
   * ----------------------------------------------------------------
   */
  basicNoneItem(val: any, operaItem: string, hasItem: string) {
    if (val && this.basicInfos[operaItem]) {
      this.basicInfos[operaItem] = '';
    }
  }

  basicOperaChange(val: any, hasItem: string) {
    if (!this.commonService.isEmpty(val) && this.basicHaves[hasItem]) {
      this.basicHaves[hasItem] = false;
    }
  }

  // 机器评估详情查看
  returnParames() {
    let tmpParams = this.routeParams.previewParams ? JSON.parse(this.routeParams.previewParams) : [];
    let params = {
      operationType: 'verifyView',
      optionIds: tmpParams.evalList.map((item: any) => item.ids) || [],
      assessTypeInfo: this.routeParams.recycleModel || {}
    };
    return params;
  }

  // 出价参考
  showOfferModal() {
    this.userEvaluationData = this.routeParams?.assessmentDetails ? JSON.parse(this.routeParams?.assessmentDetails) : {};

    if (['1', '3'].includes(this.routeParams.orderWay)) {
      this.consultLoading = true;
      const { modelId, modelName }: any = !this.commonService.isEmpty(this.routeParams.modelInfos) ? JSON.parse(this.routeParams.modelInfos) : {};
      this.offerModal.modelId = modelId;
      this.offerModal.getRecycleModelOptions(modelName);
      this.offerModal.getModelEvalDetailData();
      
      setTimeout(() => {
        this.consultLoading = false;
        this.offerModal.isVisible = true;
      }, 500);
    } else {
      this.offerModal.isVisible = true;
    }
  }

  // 设置选项背景
  setupBackground(item: any) {
    let tmpBool = false;
    if (item.optionType == 1) {
      tmpBool = item.radioSelected != '0' ? true : false;
    } else if (item.optionType == 2) {
      tmpBool = !item.options[0].checked;
      if (!item.options.some((ele: any) => ele.checked)) {
        tmpBool = false;
      }
    }

    return tmpBool;
  }

  // IMEI验证
  async verifImeiData() {
    if (this.commonService.isEmpty(this.basicInfos.imel)) {
      this.message.warning('请先输入IMEI');
      return;
    }

    let params = {
      imei: this.basicInfos.imel
    };
    const imeiId = this.message.loading('验证中..', {nzDuration: 0}).messageId;
    const {code, data, message}: any = await this.services.verificationImeiData(params);
    this.message.remove(imeiId);

    if (code === 0) {
      // 1：存在 0：不存在
      this.isHasImei = data;
    } else {
      this.message.error(message);
    }
  }

  imeiInputChange(val: any) {
    if (this.commonService.isEmpty(val)) {
      this.isHasImei = -1;
    }
  }

  // 爱思截图 截图上传
  async uploadScreenshotData() {
    try {
      if (this.screenshotUpload.uploadLoading) {
        return;
      }

      const theClipboard: any = navigator.clipboard;
      const res = await theClipboard.read();
      const imgBlob: any = await res[0].getType('image/png');
      const imgFile: File = new window.File([imgBlob], '截图.png');

      this.screenshotUpload.uploadInterface(imgFile);
    } catch (error) {
      this.message.warning('格式错误');
    }
  }
}
